
/***********************************************************************
 * Planet class
 * 
 * Implements the planet artifact
 *
 * Signature:
 *  public static Planet create (String name, Coord position);
 *  public void install ();
 *  public void destroy ();
 *  public Coord position ();
 *  public String name ();
 *  public void report (String message);
 *  public void changePosition (Coord target);
 *  public boolean isOrbitable ();
 *  public void takeDamage (int damage);
 *  public abstract char display ();
 *  public abstract String toString ();
 ***********************************************************************/
import org.json.*;

class Planet extends Artifact implements JSONString {

  protected Planet (String n, Coord p) {
    super(n,p);
  }

  public static Planet create (String n, Coord p) {
    Planet pl = new Planet(n,p);
    pl.install();
    return pl;
  }

  public char display () {
    return 'o';
  }

  public String toString () {
    return "Planet " + this.name() + " " + this.position().toString();
  }

  public boolean isOrbitable () {
    return true;
  }

  public static Planet fromJSON(JSONObject json) {
    try {
      if(json.getString("className").equals("Planet")) {
        return new Planet(json.getString("name"),
                          new Coord().fromJSON(json.getJSONObject("position")));
      } else {
        System.err.println("\"" + json.toString() + "\" does not represent a Planet.");
        throw new RuntimeException("Cannot parse JSON, it is not a Planet!");
      }
    } catch (JSONException e) {
      e.printStackTrace();
      throw new RuntimeException("Unrecoverable JSON error, see above stack trace");
    }
    
  }

  @Override
  public String toJSONString() {
    try {
      return new JSONStringer()
                        .object() 
                          .key("className")
                          .value("Planet")
                          .key("name")
                          .value(this.name())
                          .key("position")
                          .value(this.position())
                        .endObject().toString();
    } catch (JSONException e) {
      e.printStackTrace();
      throw new RuntimeException("Unrecoverable JSON error, see above stack trace.");
    }
  }
}
